//
// Note:  adding the line:
//
//    var J = jQuery.noConflict();
//
// lets you change '$' everywhere in this file to 'J'.
//
//########################################################""""""
//this is the javascript code "pm.js" which the server downloads to 
//the client (in the HTML page created by "pm.cgi"): 
//#######################################################

function show_factors(num) {
    // First reset all data
    $('.data').each(function() {
        $("#"+this.id).attr('class', 'normal data');
    });

    // Then find and show all the factors
    var nfactors = 0;
    var factors  = "";
    for (var i = 1; i < num; i++) {
        if (0 == num % i) {
            ++nfactors;
            if (factors) factors += ", ";
            factors += i;
            var tag = "#N" + i;
            $(tag).removeClass('normal').addClass('factor');
        }
    }

    // Highlight chosen square with class 'prime' or 'composite'
    var b_prime  = (nfactors > 1)? false: true;
    var newclass = (b_prime)? 'prime': 'composite';
    var tag = "#N" + num;
    $(tag).removeClass('normal').addClass(newclass);

    // Finally, explain the results
    var text;
    if (1 == num) {
        text = "The number 1 is neither prime nor composite";
    } else if (b_prime) {
        text  = "The number " + num + " is prime";
        text += " (Its only factors are 1 and itself).";
    } else {
        text  = "The number " + num + " is composite.";
        text += "  It has " + nfactors + " factors besides itself: " + factors;
    }
    $('#result').html(text);
}


function ajax_info() {
    $.ajax({
        url:       "pm.cgi",
        cache:     false,
        dataType:  "text",
        data:      { mode: 'info' },
        success:   function(result) { ajax_info_result(result); }
    });
}


function ajax_info_result(result) {
    var text   = "The server says: <b>" + result + "</b>";
    $('#info').html(text);
}
